package ru.susu.algebra.belonogov;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import ru.susu.algebra.chartable.constructor.SymmetricGroupMapTableConstructor;
import ru.susu.algebra.pair.Pair;
import ru.susu.algebra.partition.Partition;
import ru.susu.algebra.partition.PartitionsCacheConstructor;
import ru.susu.algebra.partition.filter.IPartitionFilter;
import ru.susu.algebra.partition.writer.FormattedPartitionsWriter;
import ru.susu.algebra.util.StringUtilities;

/**
 * @author akargapolov
 * @since: 04.06.2009
 */
public class MapListsPartitionsWriter extends FormattedPartitionsWriter
{
	public void write(Map<Integer, List<Pair<Partition, Partition>>> partitions, IPartitionFilter filter, String folder) throws Exception
	{
		_withNumber = false;
		SymmetricGroupMapTableConstructor constructor = SymmetricGroupMapTableConstructor.getInstance();

		for (Map.Entry<Integer, List<Pair<Partition, Partition>>> entry : partitions.entrySet())
		{
			if (entry.getValue().isEmpty())
				continue;
			System.out.println(entry.getKey());
			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(folder
					+ entry.getKey() + ".txt")));
			for (Pair<Partition, Partition> pair : entry.getValue())
			{
				this.write(Collections.singletonList(pair.getKey()), out);
				this.write(Collections.singletonList(pair.getValue()), out);
				Partition p1 = pair.getKey();
				Partition p2 = pair.getValue();

				if (!p1.getPresentedNumber().equals(p2.getPresentedNumber()))
					throw new RuntimeException("Fail!!!");

				List<Partition> altPartitions = new PartitionsCacheConstructor().getAscendingPartitions(p1
						.getPresentedNumber(), filter);

				Partition firstP = altPartitions.iterator().next();
				int width = Math.max(constructor.getValue(p1, firstP).toString().length(), constructor.getValue(p2,
						firstP).toString().length()) + 1;

				for (Partition classP : altPartitions)
				{
					out.write(StringUtilities.toString(constructor.getValue(p1, classP).toString(), width) + " : "
							+ StringUtilities.toString(constructor.getValue(p2, classP).toString(), width));
					out.write(" : ");
					classP.writeTo(out, 1);
					out.write("\n");
					out.flush();
				}
			}
			out.close();
		}
	}
}
